package com.example.lasttrain;

import java.util.ArrayList;

import com.example.lasttrain.common.DatabaseUtils;
import com.example.lasttrain.common.Defines;
import com.example.lasttrain.common.TimeData;
import com.example.lasttrain.common.TrainEntry;

import android.os.Bundle;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.text.format.Time;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.content.Intent;

public class CreateEditActivity extends Activity {

	EditText name, startStation, endStation, time;
	TimePickerDialog trainTimePickerDialog;
	Spinner alarmSpinner;
	TextView textTrainTime;
	
	int dbId, alarmFlg;
	TimeData trainTime;
	
	//検索案内トーストのためのフラグ
	boolean infoFlg = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_create_edit);

        name = (EditText)findViewById(R.id.edit_name);
        startStation = (EditText)findViewById(R.id.edit_start);
        endStation = (EditText)findViewById(R.id.edit_end);
        //trainTimePicker = (TimePicker)findViewById(R.id.train_time_picker);
        alarmSpinner = (Spinner)findViewById(R.id.alarm_spinner);
        textTrainTime = (TextView)findViewById(R.id.text_train_time);
        
        ArrayAdapter timeAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_time, android.R.layout.simple_spinner_item);
        
        timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        Spinner timeSpinner = (Spinner) findViewById(R.id.alarm_spinner);
        
        timeSpinner.setAdapter(timeAdapter);
        
        
        if(getIntent().hasExtra(Defines.INTENT_DB_NUMBER)){ //get the station information from DB, if the intent has an available DB id...
        	//TrainEntry editEntry = new TrainEntry();
        	
        	dbId = getIntent().getIntExtra(Defines.INTENT_DB_NUMBER, 0);
        	TrainEntry editEntry = DatabaseUtils.getContents(this, dbId);
        	
        	name.setText(editEntry.getName());
        	startStation.setText(editEntry.getStartStation());
        	endStation.setText(editEntry.getEndStation());
        	//trainTimePicker.setCurrentHour(editEntry.getTrainTime().getHour());
        	//trainTimePicker.setCurrentMinute(editEntry.getTrainTime().getMinute());
        	alarmSpinner.setSelection(editEntry.getAlarmtime());
        	alarmFlg = editEntry.getAlarmFlg();
        	trainTime = editEntry.getTrainTime();
        }
        else {
        	dbId = 0;
        	
            Time currentTime = new Time();
            currentTime.setToNow();
            trainTime = new TimeData(currentTime.hour, currentTime.minute);
        }
        
        Button button1=(Button)findViewById(R.id.syuden_kensaku);
        button1.setOnClickListener(new OnClickListener(){
         @Override
           public void onClick(View v) {
        	 
        	 if(!infoFlg)
        	 {
        		 //Toast.makeText(v.getContext(), R.string.search_info, Toast.LENGTH_SHORT).show();
        		 infoFlg = true;
        	 }
        	 
               Intent intent = new Intent(CreateEditActivity.this, JorudanViewActivity.class);
               startActivity(intent);
          }
        });
    }
    
    private void updateTrainTimeText(){
    	if(trainTime == null) return;
    	// 時間や分が1桁の場合は0で補完する
    	String trainTimeHour = Integer.toString(trainTime.getHour());
    	String trainTimeMinute = Integer.toString(trainTime.getMinute());
    	if(trainTime.getHour()<9){
    		trainTimeHour = "0" + trainTimeHour;
    	}
    	if(trainTime.getMinute()<9){
    		trainTimeMinute = "0" + trainTimeMinute;
    	}
    	textTrainTime.setText(trainTimeHour + " : " + trainTimeMinute);
    }
    
    
    
    @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateTrainTimeText();
	}

	private boolean moveToDetailActivity(){
    	
    	String strName = null, strStart =null, strEnd = null;
    	//TimeData time = null;
    	int alarmSet = 0;
    	
    	strName = name.getText().toString();
    	strStart = startStation.getText().toString();
    	strEnd = endStation.getText().toString();
    	//time = new TimeData(trainTimePicker.getCurrentHour(), trainTimePicker.getCurrentMinute());
    	alarmSet = alarmSpinner.getSelectedItemPosition();
    	
    	if(strName.length()==0 || strStart.length()==0 || strEnd.length()==0)
    		return false;
    	
    	TrainEntry entry = new TrainEntry(strName, dbId, trainTime, strStart, strEnd, alarmSet, alarmFlg);
    	TrainEntry.setNewEntry(entry);
    	
    	Intent intent = new Intent(this, DetailActivity.class);
		startActivityForResult(intent, 0);

    	return true;
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		setResult(resultCode);
		
		if(resultCode == RESULT_OK)
			finish();
	}
    
    private boolean saveTrainInformation(){
    	
    	String strName = null, strStart =null, strEnd = null;
    	//TimeData time = null;
    	int alarmSet = 0;
    	
    	strName = name.getText().toString();
    	strStart = startStation.getText().toString();
    	strEnd = endStation.getText().toString();
    	//time = new TimeData(trainTimePicker.getCurrentHour(), trainTimePicker.getCurrentMinute());
    	alarmSet = alarmSpinner.getSelectedItemPosition();
    	
    	if(strName.length()==0 || strStart.length()==0 || strEnd.length()==0)
    		return false;
    	
    	TrainEntry entry = new TrainEntry(strName, dbId, trainTime, strStart, strEnd, alarmSet);
    	//save data to DB at here...
    	DatabaseUtils.upRecord(this, entry);
    	
    	
    	return true;
    }

	public void mOnClick(View v){

		switch(v.getId()){
		case R.id.button_ok:
			if(false == moveToDetailActivity())
				Toast.makeText(this, R.string.notice_fail, Toast.LENGTH_SHORT).show();
			break;
			
		case R.id.button_cancel:
			finish();
			break;
			
		case R.id.text_train_time:
			
			trainTimePickerDialog = new TimePickerDialog(CreateEditActivity.this,
					new TimePickerDialog.OnTimeSetListener() {
						@Override
						public void onTimeSet(TimePicker view, int hourOfDay, int minute){
							trainTime = new TimeData(hourOfDay, minute);
							updateTrainTimeText();
						}
					},
					trainTime.getHour(),
					trainTime.getMinute(),
					true);
			trainTimePickerDialog.show();
			
			
		}

    }    
}
